package com.htd.erp.web;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.lang3.StringUtils;

/**
 * @author Zhang Guilin
 */
@Named
@SessionScoped
public class Navigator implements Serializable {

	private static final long serialVersionUID = 182097765166045894L;
	
	private Map<String, Menu> VIEW_MENU_MAP = new HashMap<String, Menu>();
	
	@Inject
	@Named("rootMenu")
	private Menu rootMenu;

	private String lastViewId;
	
	private Menu lastMenu;
	
	@PostConstruct
	public void postConstruct() {
		fillMenuMap(rootMenu);
	}
	
	public Menu getActiveMenu() {
		String viewId = FacesContext.getCurrentInstance().getViewRoot().getViewId();
		if(StringUtils.equals(lastViewId, viewId)) {
			return lastMenu;
		}
		lastMenu = getActiveMenu(viewId);
		lastViewId = viewId;
		return lastMenu;
	}
	
	protected Menu getActiveMenu(String viewId) {
		return VIEW_MENU_MAP.get(viewId);
	}
	
	private void fillMenuMap(Menu menu) {
		if(StringUtils.isNotBlank(menu.getHref())) {
			VIEW_MENU_MAP.put(menu.getHref(), menu);
		}
		for(Menu subMenu : menu.getSubMenus()) {
			fillMenuMap(subMenu);
		}
	}
}
